package com.wisdytech.linkdcs.equipLifeCycle.maintain.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.PageInfo;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.constants.CommonConstants;
import com.wisdytech.common.exception.ServiceException;
import com.wisdytech.common.handler.BaseService;
import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.dao.RepairPlanDao;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.dao.RepairPlanRefDao;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.model.RepairPlan;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.model.RepairPlanRef;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.service.IRepairPlanService;
import com.wisdytech.linkdcs.equipment.model.Equipment;
import com.wisdytech.linkdcs.partLife.dao.IPartDao;
import com.wisdytech.linkdcs.partLife.model.Part;
import com.wisdytech.linkdcs.system.model.SysUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhanghailin
 * @since 2018-07-17
 */
@Service
@Transactional
public class RepairPlanServiceImpl extends BaseService<RepairPlanDao, RepairPlan> implements IRepairPlanService {

    @Resource
    private RepairPlanDao repairPlanDao;

    @Resource
    private RepairPlanRefDao repairPlanRefDao;


    @Override
    public PageInfo<RepairPlan> findRepairPlanByPage(String equipCode, String equipName, String maintenanceProject, String dutyDepartment, String maintenanceStartDate, String maintenanceEndDate, Filter filter) {
        Map<String, Object> params = new HashMap<>();
        if(StringUtils.isNotBlank(equipCode)) {
            params.put("equipCode",equipCode);
        }
        if(StringUtils.isNotBlank(equipName)) {
            params.put("equipName",equipName);
        }
        if(StringUtils.isNotBlank(maintenanceProject)) {
            params.put("maintenanceProject",maintenanceProject);
        }
        if(StringUtils.isNotBlank(dutyDepartment)) {
            params.put("dutyDepartment",dutyDepartment);
        }
        if(StringUtils.isNotBlank(maintenanceStartDate)) {
            params.put("maintenanceStartDate",maintenanceStartDate);
        }
        if(StringUtils.isNotBlank(maintenanceEndDate)) {
            params.put("maintenanceEndDate",maintenanceEndDate);
        }
        List<RepairPlan> list = super.beforeList(RepairPlanDao.class,filter).selectRepairPlanList(params);
        list.forEach(repairPlan -> {
            if (StringUtils.isNotBlank(repairPlan.getPkId())) {
                //查询关联的工装
                repairPlan.setToolList(this.repairPlanRefDao.selectToolByPlanId(repairPlan.getPkId()));
                //查询关联的备件
                repairPlan.setPartList(this.repairPlanRefDao.selectPartByPlanId(repairPlan.getPkId()));
            }
        });
        return new PageInfo<>(list);
    }

    @Override
    public void saveOrUpdateRepairPlan(RepairPlan repairPlan, SysUser sysUser) {
        Optional<SysUser> sysUserOptional = Optional.ofNullable(sysUser);
        sysUserOptional.orElseThrow(() -> new ServiceException("操作人不能为空"));
        Optional<RepairPlan> repairPlanOptional = Optional.ofNullable(repairPlan);
        repairPlanOptional.orElseThrow(() -> new ServiceException("检修计划不能为空"));
        repairPlanOptional
                .map(RepairPlan::getEquipCode)
                .filter(StringUtils::isNotBlank)
                .orElseThrow(() -> new ServiceException("设备不能为空"));
        //update
        if (StringUtils.isNotBlank(repairPlan.getPkId())) {
            repairPlan.setUpdateDate(new Date());
            repairPlan.setUpdateUser(sysUser.getUsername());
            this.repairPlanDao.updateById(repairPlan);
            if (StringUtils.isNotBlank(repairPlan.getToolIds())) {
                //先删除工装，在新增
                EntityWrapper<RepairPlanRef> deleteToolEw = new EntityWrapper<>();
                deleteToolEw.eq("plan_id",repairPlan.getPkId()).eq("type","1");
                repairPlanRefDao.delete(deleteToolEw);

                //先删除备件，在新增
                EntityWrapper<RepairPlanRef> deletePartEw = new EntityWrapper<>();
                deletePartEw.eq("plan_id",repairPlan.getPkId()).eq("type","2");
                repairPlanRefDao.delete(deletePartEw);
            }
        } else {
            //insert
            repairPlan.setPkId(BaseUtil.getUUID());
            repairPlan.setCreateUser(sysUser.getUsername());
            repairPlan.setCreateDate(new Date());
            repairPlan.setDelFlag(CommonConstants.DEL_FLAG);
            this.repairPlanDao.insert(repairPlan);

        }
        //插入关联工装信息
        String[] toolIds = repairPlan.getToolIds().split(",");
        if(toolIds.length>0 && repairPlan.getToolIds()!=""){
            Arrays.stream(toolIds).forEach(toolId -> {
                RepairPlanRef repairPlanRef = new RepairPlanRef();
                repairPlanRef.setCreateDate(new Date());
                repairPlanRef.setDelFlag(CommonConstants.DEL_FLAG);
                repairPlanRef.setType("1");//表示工装
                repairPlanRef.setCreateUser(sysUser.getUsername());
                repairPlanRef.setRefId(toolId);
                repairPlanRef.setPlanId(repairPlan.getPkId());
                repairPlanRef.setPkId(BaseUtil.getUUID());
                repairPlanRefDao.insert(repairPlanRef);
            });
        }
        //插入关联备件信息
        String[] partIds = repairPlan.getPartIds().split(",");
        if (partIds.length>0 && repairPlan.getPartIds()!=""){
            Arrays.stream(partIds).forEach(partId -> {
                RepairPlanRef repairPlanRef = new RepairPlanRef();
                repairPlanRef.setCreateDate(new Date());
                repairPlanRef.setDelFlag(CommonConstants.DEL_FLAG);
                repairPlanRef.setType("2");//表示备件
                repairPlanRef.setCreateUser(sysUser.getUsername());
                repairPlanRef.setRefId(partId);
                repairPlanRef.setPlanId(repairPlan.getPkId());
                repairPlanRef.setPkId(BaseUtil.getUUID());
                repairPlanRefDao.insert(repairPlanRef);
            });
        }
    }

    @Override
    public PageInfo<Part> findPartByPage(String search, Filter filter) {
        EntityWrapper<Part> ew = new EntityWrapper<>();
        ew.setSqlSelect("pk_id","part_name","part_code");
        ew.eq("del_flag",CommonConstants.DEL_FLAG);
        if (StringUtils.isNotBlank(search)) {
            ew.andNew()
                    .like("part_code",search)
                    .or()
                    .like("part_name",search);
        }
        List<Part> list = super.beforeList(IPartDao.class,filter).selectList(ew);
        return new PageInfo<>(list);
    }

    @Override
    public void logicDeleteRepairPlanByPkIds(String pkIds) {
        if (StringUtils.isBlank(pkIds))
            return;
        String[] pkIdArray = pkIds.split(",");
        RepairPlan repairPlan = new RepairPlan();
        repairPlan.setDelFlag(CommonConstants.DEL_FLAG_TRUE);
        Arrays.stream(pkIdArray).forEach(pkId -> {
            repairPlan.setPkId(pkId);
            repairPlanDao.updateById(repairPlan);
        });
    }

    @Override
    public RepairPlan findRepairPlanById(String pkId) {
        if (StringUtils.isBlank(pkId)) {
            return null;
        }
        RepairPlan repairPlan = this.repairPlanDao.selectRepairPlanById(pkId);
        if (repairPlan == null) {
            return null;
        }
        //查询关联的工装
        repairPlan.setToolList(this.repairPlanRefDao.selectToolByPlanId(pkId));
        //查询关联的备件
        repairPlan.setPartList(this.repairPlanRefDao.selectPartByPlanId(pkId));
        return repairPlan;
    }

    @Override
    public Equipment fingEquipInfoByEquipCode(String equipCode) {
        if (StringUtils.isBlank(equipCode))
            return null;
        return this.repairPlanDao.selectEquipInfoByCode(equipCode);
    }
}
